import Vue from 'vue'
import Main from './main.vue'
import * as Options from './defaultOptions'
import { api } from '~/ui-domain'

let PurchasePlanConstructor = Vue.extend(Main)

let instance
let seed = 1

const PurchasePlan = function(options) {
  if (Vue.prototype.$isServer) return
  if (instance) instance.close()

  return new Promise((resolve, reject) => {
    options = options || {}
    if (!options.purchasePlanApi) {
      options.purchasePlanApi = `${api.admin}/admin/erp/product`
    }
    let id = 'purchasePlan_picker_' + seed++
    options.show = true
    instance = new PurchasePlanConstructor({ propsData: options })
    instance.id = id
    instance.$mount()
    instance.resolve = resolve
    instance.reject = reject
    instance.close = closeInstance
    document.body.appendChild(instance.$el)
  })
}

// 扩展列
PurchasePlan.columns = {
  general: Options.generalColumns
}

function closeInstance() {
  instance.$destroy()
  instance.$el.parentNode.removeChild(instance.$el)
  instance.reject('取消了')
  instance = undefined
}

export default PurchasePlan
